package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.SoulConclusion;
import com.itheima.domain.db.SoulDimensions;
import com.itheima.domain.db.SoulQuestionOptions;
import com.itheima.domain.db.SoulQuestions;
import com.itheima.domain.vo.*;
import com.itheima.service.db.SoulTestService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class SoulTestManager {

    @Reference
    private SoulTestService soulTestService;

    @Autowired
    private OssTemplate ossTemplate;

    private static List<String> letterList = new ArrayList<>();

    static {
        letterList.add("A");
        letterList.add("B");
        letterList.add("C");
        letterList.add("D");
        letterList.add("E");
        letterList.add("F");
        letterList.add("G");
    }

    //分页查询所有测试题
    public PageBeanVo findTest(Integer page, Integer limit, String startDate, String endDate, String category) {
        //根据分页查询到所有的问题
        PageBeanVo pageBeanVo = soulTestService.findQuestionByPage(page, limit,startDate,endDate,category);
        //获取对象中的结果集
        List<SoulQuestions> items = (List<SoulQuestions>) pageBeanVo.getItems();

        //创建集合保存结果集
        List<SoulQuestionsVo> resultList = new ArrayList<>();

        //对集合进行非空判断
        if (CollectionUtil.isNotEmpty(items)) {
            //遍历集合
            for (SoulQuestions soulQuestions : items) {
                //根据题目id查询选项
                List<SoulQuestionOptions> optionsList = soulTestService.findOptionsByQuestionId(soulQuestions.getId());

                //创建返回值对象
                SoulQuestionsVo soulQuestionsVo = new SoulQuestionsVo();
                soulQuestionsVo.setId(soulQuestions.getId());
                soulQuestionsVo.setName(soulQuestions.getQuestion());

                String opstionStr = "";
                //对选项的返回值结果进行非空判断
                if (CollectionUtil.isNotEmpty(optionsList)) {
                    //遍历集合
                    for (int i = 0; i < optionsList.size(); i++) {
                        opstionStr = opstionStr + (i + 1 + "、") + optionsList.get(i).getOptions() + "--" + optionsList.get(i).getScore() + " ";
                    }
                }

                //将拼接的选项字符串添加到返回值对象
                soulQuestionsVo.setOptions(opstionStr);
                //赋值时间

                String created = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(soulQuestions.getCreated());
                soulQuestionsVo.setCreated(created);
                soulQuestionsVo.setCategory(soulQuestions.getStar());
                //将返回值对象添加到集合中
                resultList.add(soulQuestionsVo);
            }
        }

        //将返回值集合重新赋值
        pageBeanVo.setItems(resultList);

        //返回对象
        return pageBeanVo;
    }

    //修改回显
    public QuestionAndOptionsVo findQuestionAndOptions(Long id) {
        //根据ID查询题目
        SoulQuestions soulQuestions = soulTestService.findQuestionById(id);
        //对返回值进行非空判断
        if (soulQuestions != null) {
            //根据题目查询选项
            List<SoulQuestionOptions> options = soulTestService.findOptionsByQuestionId(soulQuestions.getId());

            //创建集合保存选项对象
            List<OptionsVo> voList = new ArrayList<>();

            //对集合进行非空判断
            if (CollectionUtil.isNotEmpty(options)) {
                //遍历集合
                for (SoulQuestionOptions option : options) {
                    //创建选项的vo对象
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setOptionName(option.getOptions());
                    optionsVo.setScore(option.getScore());
                    //添加到集合中
                    voList.add(optionsVo);
                }
            }

            //创建返回值对象
            QuestionAndOptionsVo questionAndOptionsVo = new QuestionAndOptionsVo();
            questionAndOptionsVo.setName(soulQuestions.getQuestion());
            questionAndOptionsVo.setId(soulQuestions.getId());
            questionAndOptionsVo.setCategory(soulQuestions.getStar());
            questionAndOptionsVo.setOptions(voList);

            //返回返回值
            return questionAndOptionsVo;
        }
        return null;
    }

    //根据id删除问题
    public Map deleteQuestionById(Long id) {
        //根据id删除题目
        soulTestService.deleteQuestion(id);
        //根据题目id查询选项
        List<SoulQuestionOptions> options = soulTestService.findOptionsByQuestionId(id);
        //遍历集合
        for (SoulQuestionOptions option : options) {
            //根据选项id进行删除
            soulTestService.deleteOptionById(option.getId());
        }
        //封装返回值
        Map<String, String> map = new HashMap<>();
        map.put("massage", "删除成功");
        return map;
    }

    //修改题目
    public Map updateQuestion(Map<String, String> map) {
        //根据题目id查询该题目的相关信息
        String id = map.get("id");
        SoulQuestions question = soulTestService.findQuestionById(Long.valueOf(id));
        question.setQuestion(map.get("name"));
        String category = map.get("category");
        question.setStar(Integer.valueOf(category));
        //调用方法修改问题
        soulTestService.updateQuestion(question);

        //创建集合保存选项
        List<String> optionList = new ArrayList<>();
        List<Integer> scoreList = new ArrayList<>();

        Set<String> keySet = map.keySet();//获取map的键
        //遍历map的键
        for (String key : keySet) {
            if (letterList.contains(key)) {
                optionList.add(map.get(key));
                scoreList.add(Integer.valueOf(map.get("score" + key)));
            }
        }

        //根据题目id查询所有的选项
        List<SoulQuestionOptions> options = soulTestService.findOptionsByQuestionId(Long.valueOf(id));
        //删除该题所有选项
        for (SoulQuestionOptions option : options) {
            soulTestService.deleteOptionById(option.getId());
        }
        //重新创建该题的选项
        for (int i = 0; i < optionList.size(); i++) {
            SoulQuestionOptions soulQuestionOptions = new SoulQuestionOptions();
            soulQuestionOptions.setQuestionId(Long.valueOf(id));
            soulQuestionOptions.setOptions(optionList.get(i));
            soulQuestionOptions.setScore(scoreList.get(i));
            //调用方法保存
            soulTestService.saveOptions(soulQuestionOptions);
        }

        //封装返回值
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("massage", "修改成功");
        return resultMap;
    }

    //新增题目
    public Map addQuestionAndOptions(Map<String, String> map) {
        //根据题目id查询该题目的相关信息

        String name = map.get("name");
        Integer category = Integer.valueOf(map.get("category"));
        SoulQuestions question = soulTestService.findQuestion(name,category);
        if (question != null) {
                throw new RuntimeException("数据已存在！");
        }

        SoulQuestions soulQuestions = new SoulQuestions();
        soulQuestions.setStar(category);
        soulQuestions.setQuestion(name);

        //调用方法保存题目
        soulTestService.saveQuestion(soulQuestions);
        //再次查询该问题
        SoulQuestions newQuestion = soulTestService.findQuestion(name, category);
        if (newQuestion == null) {
            throw new RuntimeException("添加失败");
        }
        //创建集合保存选项
        List<String> optionList = new ArrayList<>();
        List<Integer> scoreList = new ArrayList<>();

        Set<String> keySet = map.keySet();//获取map的键
        //遍历map的键
        for (String key : keySet) {
            if (letterList.contains(key)) {
                optionList.add(map.get(key));
                scoreList.add(Integer.valueOf(map.get("score" + key)));
            }
        }

        //创建该题的选项
        for (int i = 0; i < optionList.size(); i++) {
            SoulQuestionOptions soulQuestionOptions = new SoulQuestionOptions();
            soulQuestionOptions.setQuestionId(newQuestion.getId());
            soulQuestionOptions.setOptions(optionList.get(i));
            soulQuestionOptions.setScore(scoreList.get(i));
            //调用方法保存
            soulTestService.saveOptions(soulQuestionOptions);
        }

        //封装返回值
        Map<String, String> resultMap = new HashMap<>();
        map.put("massage", "添加成功");
        return resultMap;

    }

    //分页查询测试报告
    public PageBeanVo findTestReport(Integer page, Integer limit) {
        //分页查询所有报告
        PageBeanVo pageBeanVo = soulTestService.findTestReport(page, limit);
        //获取返回值中的结果集
        List<SoulConclusion> items = (List<SoulConclusion>) pageBeanVo.getItems();

        //创建集合保存返回值对象
        List<SoulReportVo> voList = new ArrayList<>();

        //对集合进行非空判断
        if (CollectionUtil.isNotEmpty(items)) {
            //遍历集合
            for (SoulConclusion soulConclusion : items) {
                //根据soulConclusion中的dimensions查询查询该报表维度
                SoulDimensions soulDimensions = soulTestService.findDimensionsById(soulConclusion.getDimensions());

                //创建SoulReportVo对象
                SoulReportVo soulReportVo = new SoulReportVo();
                BeanUtil.copyProperties(soulDimensions, soulReportVo);
                BeanUtil.copyProperties(soulConclusion, soulReportVo);
                soulReportVo.setSoulAbstract(soulDimensions.getSoulAbstract());
                String format = new SimpleDateFormat("yyyy-MM-dd").format(soulConclusion.getCreated());
                soulReportVo.setCreated(format);
                //将对象保存到返回值对象集合
                voList.add(soulReportVo);
            }
        }

        //重新赋值PageBeanVo
        pageBeanVo.setItems(voList);
        //返回对象
        return pageBeanVo;
    }

    //修改报告
    public Map updateReport(SoulReportVo soulReportVo, MultipartFile multipartFile) throws IOException {
        //保存图片
        String coverUrl = null;
        if (multipartFile != null) {
            coverUrl = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
        }

        //根据id查询报告
        SoulConclusion conclusion = soulTestService.findReportById(soulReportVo.getId());
        conclusion.setConclusion(soulReportVo.getConclusion());
        conclusion.setCover(coverUrl);
        conclusion.setScoreInterval(soulReportVo.getScoreInterval());
        //调用方法进行保存
        soulTestService.updateConclusion(conclusion);
        //查询维度
        SoulDimensions soulDimensions = soulTestService.findDimensionsById(conclusion.getDimensions());
        soulDimensions.setExtroversion(soulReportVo.getExtroversion());
        soulDimensions.setJudge(soulReportVo.getJudge());
        soulDimensions.setReason(soulReportVo.getReason());
        soulDimensions.setSoulAbstract(soulReportVo.getSoulAbstract());
        //调用方法保存
        soulTestService.updateDimensions(soulDimensions);

        //
        //封装返回值
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("massage", "修改成功");
        return resultMap;
    }
}
